package ltd.dujiabao.dex.quartz.exe;

import java.lang.reflect.Method;
import java.sql.Date;
import java.time.Instant;

import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.dex.core.DelayJobEntity;
import ltd.dujiabao.dex.core.emitter.Emitter;

/**
 * @author : DuJiabao
 * @Project : common-delay-executor
 * @Time : 2024/3/30 13:54
 * @Desc :
 */
@Slf4j
public class QuartzEmitter implements Emitter {
    private final Scheduler scheduler;
    private final DelayJobEntity delayJob;

    public QuartzEmitter(DelayJobEntity delayJob, Scheduler scheduler) {
        this.delayJob = delayJob;
        this.scheduler = scheduler;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("delayJob", delayJob);
        jobDataMap.put("method", method);
        jobDataMap.put("args", args);

        JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class)
                .setJobData(jobDataMap)
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(Date.from(Instant.now().plusSeconds(delayJob.delayTimeInSec())))
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
        return null;
    }
}
